package com.dtjd.playcoinmonkey.activities;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.dtjd.playcoinmonkey.adapter.NoticeAdapter;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.bean.NoticeBean;
import com.dtjd.playcoinmonkey.databinding.ActivityNoticeBinding;
import com.dtjd.playcoinmonkey.utils.Network;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class NoticeActivity extends AppCompatActivity {
    private NoticeAdapter adp;
    private final List<NoticeBean> data=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityNoticeBinding binding = ActivityNoticeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ActionBar actionbar = getSupportActionBar();
        if (actionbar!=null){
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setHomeButtonEnabled(true);
        }
        String title = getIntent().getStringExtra("title");
        setTitle(title);
        adp=new NoticeAdapter(this,data);
        binding.noticeList.setAdapter(adp);
        refresh(getIntent().getBooleanExtra("isWarn",true));
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        return super.onOptionsItemSelected(item);
    }
    private void refresh(boolean isWarn) {
        data.clear();
        List<HttpParaBean> para=new ArrayList<>();
        para.add(new HttpParaBean("getOne","false"));
        Network.post(para, "wbhMain/"+(isWarn?"getWarn":"getNotice"), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
             e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(() -> {
                    try {
                        JSONArray ja = new JSONObject(response.body().string()).getJSONArray("datalist");
                        for (int i = 0; i < ja.length(); i++) {
                            JSONObject jo = ja.getJSONObject(i);
                            data.add(new NoticeBean(false,jo.getString("id"),jo.getString("time"),jo.getString("content")));
                        }
                        adp.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
}